<template>
  <el-form
    ref="form"
    :label-position="labelPosition"
    :label-width="labelWidth"
    :model="form"
    class="bold-label"
  >
    <el-form-item label="我的标签">
      <component-edit-tags v-show="editing" :tags.sync="form.tags" :editing="editing" />
      <div v-show="!editing">
        <el-tag v-for="tag in form.tags" :key="tag" disable-transitions style="color: #121212;">
          {{ tag }}</el-tag>
        <field-modify-button
          v-model="editing"
          :always-display="!form.tags.length"
          :label="form.tags.length ? '修改' : '添加'"
        />
      </div>
    </el-form-item>
    <el-form-item v-show="editing">
      <field-submit-buttons :loading="loading" @submit="updateInfo" @cancel="cancel" />
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatUser } from '@/views/users/format';
import FieldModifyButton from '@/views/users/edit/components/field-modify-button';
import FieldSubmitButtons from '@/views/users/edit/components/field-submit-buttons';
import ComponentEditTags from '@/views/users/edit/components/component-edit-tags';

export default {
  name: 'form-tags',
  components: {
    FieldModifyButton,
    FieldSubmitButtons,
    ComponentEditTags,
  },
  props: {
    labelPosition: { // top left right
      type: String,
      default: 'left',
    },
    labelWidth: {
      type: String,
      default: '140px',
    },
  },
  data() {
    return {
      form: {
        tags: [],
      },
      loading: false,
      editing: false,
    };
  },
  computed: {
    ...mapState({ curUser: 'currentUser' }),
    // 更新用户信息所需参数
    updateInfoParams() {
      return {
        userId: this.curUser.id,
        tags: this.form.tags,
      };
    },
  },
  created() {
    this.resetForm();
  },
  methods: {
    ...mapActions({ setCurUser: 'setCurrentUser' }),
    // 更新用户信息
    updateInfo() {
      this.loading = true;
      this.$api.users.update(this.updateInfoParams)
        .then((res) => {
          this.$message.success('修改成功');
          this.setCurUser(Object.assign(formatUser(res.data), { token: this.curUser.token }));
          this.editing = false;
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 取消更新
    cancel() {
      this.resetForm();
      this.editing = false;
    },
    // 重置用户信息
    resetForm() {
      this.$set(this.form, 'tags', this.curUser.tags);
    },
  },
};
</script>

<style></style>
